﻿// Functions - General 

// function to show incomplete alert
function showIncomplete() {
    var incomplete = document.getElementById("incomplete");
    if (incomplete){
        incomplete.style.display = "block";
    }
}

// function to take an xml returned date and return an array of its elements
function parseXMLDate(value) {
    if (value) {
        var dateTimeSplit = value.split('T');
        var date = dateTimeSplit[0];
        var time = dateTimeSplit[1];
        
        var dateSplit = date.split('-');
        var timeSplit = time.split(':');
        
        var dateTimeArray = [];
        dateTimeArray.push(dateSplit[0]);  // year
        dateTimeArray.push(dateSplit[1]);  // month
        dateTimeArray.push(dateSplit[2]);  // day
        dateTimeArray.push(timeSplit[0]);  // hours
        dateTimeArray.push(timeSplit[1]);  // minutes
        dateTimeArray.push(timeSplit[2]);  // seconds
        
        return dateTimeArray;
    }
    return null;
}

// function to update get info panel on list pages
var getInfoRequest = new XMLHttpRequest();
var activeInfoPanel = null;
function requestGetInfo (dbId, level, infoPanel) {
    activeInfoPanel = infoPanel;
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_GetInfo\" ID=\"" + dbId + "\" Level=\"" + level + "\" />";
    callAjaxPost(getInfoRequest, sProc, processGetInfoRequest);	
}

// function to process get info request
function processGetInfoRequest () {
    if (getInfoRequest.readyState == 4) {
		if (getInfoRequest.status == 200) {
			if (getInfoRequest.responseXML != null) {
			    // delete any previous contents
			    var currentEls = activeInfoPanel.immediateDescendants();
			    for (var i=0, len=currentEls.length; i<len; i++) {
			        currentEls[i].remove();
			    }
			    
			    // loop through returned xml and display info
			    var infoEls = getInfoRequest.responseXML.getElementsByTagName('GetInfo');
			    for (var i=0, len=infoEls.length; i<len; i++) {
			        var label = document.createElement('dt');
			        label.innerHTML = infoEls[i].getAttribute('Name') + ": ";
			        var description = document.createElement('dd');
			        description.innerHTML = infoEls[i].getAttribute('Value');
			        activeInfoPanel.appendChild(label);
			        activeInfoPanel.appendChild(description);
			    }
			    // reset info panel
			    activeInfoPanel = null;
			}
		}
	} 
}

// function to hide duplicate popup
function hideDuplicateAs(){
    uncoverPageForAlert();
    $('dupObject').style.display = "none";
}

// function to show duplicate popup
var activeMsgNode = null;
function showDuplicateAs(strObject, name, dbId, msgNode) {   
    // set success node here - can't pass through onclick
    activeMsgNode = msgNode;
    $('dupAlert').style.display = "none";
    var duplicate = $('dupObject');
    switch (strObject) {
        case "asset"    : $('dupSpan').innerHTML = "Duplicate Asset As...";
                          $('dupLabel').innerHTML = "New Asset Name";
                          $('dupName').value = name + "_Dup";
                          $('dupBtn').setAttribute('onclick', 'requestDuplicateObject(' + dbId + ', 4);');
                          break;
        case "combo"    : $('dupSpan').innerHTML = "Duplicate Combo As...";
                          $('dupLabel').innerHTML = "New Combo Name";
                          $('dupName').value = name + "_Dup";
                          $('dupBtn').setAttribute('onclick', 'requestDuplicateObject(' + dbId + ', 3);');
                          break;            
        case "event"    : $('dupSpan').innerHTML = "Duplicate Event As...";
                          $('dupLabel').innerHTML = "New Event Name";
                          $('dupName').value = name + "_Dup";
                          $('dupBtn').setAttribute('onclick', 'requestDuplicateObject(' + dbId + ', 2);');
                          break; 
        case "package"  : $('dupSpan').innerHTML = "Duplicate Package As...";
                          $('dupLabel').innerHTML = "New Package Name";
                          $('dupName').value = name + "_Dup";
                          $('dupBtn').setAttribute('onclick', 'requestDuplicateObject(' + dbId + ', 1);');
                          break; 
        case "schedule" : $('dupSpan').innerHTML = "Duplicate Schedule As...";
                          $('dupLabel').innerHTML = "New Schedule Name";
                          $('dupName').value = name + "_Dup";
                          $('dupBtn').setAttribute('onclick', 'requestDuplicateObject(' + dbId + ', 0);');
                          break; 
        default         : alert("switch on default");           
    }
    duplicate.style.display = "block";
    // cover page
    coverPageForAlert(duplicate);
}

var dupObjRequest = new XMLHttpRequest();
function requestDuplicateObject(dbId, level) { 
    var errMsg = "";
    // check required fields
    if ($('dupName').value.strip() == '') {
        if (level == 1) errMsg = "&#149; Package name is a required field"
        else if (level == 2) errMsg = "&#149; Event name is a required field"
        else if (level == 3) errMsg = "&#149; Combo name is a required field"
        else if (level == 4) errMsg = "&#149; Asset name is a required field"
    }
    if (errMsg != '') {
        var alertEl = $('dupAlert');
        alertEl.innerHTML = errMsg;
        $('dupAlert').style.display = "block";
        return;
    }
    // check for unique name
    if (!checkUniqueName (dbId, $('dupName').value.strip(), level)) {
        var alertEl = $('dupAlert');
        if (level == 1) errMsg = "&#149; A package with this name already exists"
        else if (level == 2) errMsg = "&#149; An event with this name already exists"
        else if (level == 3) errMsg = "&#149; A combo with this name already exists"
        else if (level == 4) errMsg = "&#149; An asset with this name already exists"
        alertEl.innerHTML = errMsg;
        var name = $('dupName').value.strip();
        $('dupName').value = name + "_";
        $('dupAlert').style.display = "block";
        return;
    }
    
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_DuplicateObj\" objID=\"" + dbId + "\" objLevel=\"" + level + "\" " +
                    "objNewName=\"" + escapeForXML($('dupName').value.strip()) + "\" />";
    callAjaxPost(dupObjRequest, sProc, processDuplicateObjectRequest);	
    hideDuplicateAs(); 
}

// function to process duplicate object request
function processDuplicateObjectRequest () {
    if (dupObjRequest.readyState == 4) {
		if (dupObjRequest.status == 200) {
			activeMsgNode.style.fontWeight = "bold";
			activeMsgNode.style.color = "Green";
			var alertStr = "";
			if (activeMsgNode.id.match('Package')) alertStr = "Package successfully duplicated";
            else if (activeMsgNode.id.match('Event')) alertStr = "Event successfully duplicated";
            else if (activeMsgNode.id.match('Combo')) alertStr = "Combo successfully duplicated";
            else if (activeMsgNode.id.match('Asset')) alertStr = "Asset successfully duplicated";
			activeMsgNode.innerHTML = alertStr;
			activeMsgNode.style.display = "block";
			// reset message node
			activeMsgNode = null;
		}
	} 
}

var thisEnabledRequest = new XMLHttpRequest();
function requestEnableDisable(dbId, level, thisEnabled, msgNode) {
    activeMsgNode = msgNode;    
    var sProc = "<STOREDPROCEDURE Name=\"sproc_WEB_EnableDisableObj\" ID=\"" + dbId + "\" Level=\"" + level + "\" " +
                    "ThisEnabled=\"" + thisEnabled + "\" />";
    if (thisEnabled == true) {
        callAjaxPost(thisEnabledRequest, sProc, processEnableRequest);
    } else {
        callAjaxPost(thisEnabledRequest, sProc, processDisableRequest);
    }
}

// function to process duplicate object request
function processEnableRequest () {
    if (thisEnabledRequest.readyState == 4) {
		if (thisEnabledRequest.status == 200) {
		    if (thisEnabledRequest.responseText != 0 ) {
			    activeMsgNode.style.fontWeight = "bold";
			    activeMsgNode.style.color = "Green";
			    var alertStr = "";
			    if (activeMsgNode.id.match('Package')) alertStr = "Package successfully enabled";
                else if (activeMsgNode.id.match('Event')) alertStr = "Event successfully enabled";
                else if (activeMsgNode.id.match('Combo')) alertStr = "Combo successfully enabled";
                else if (activeMsgNode.id.match('Asset')) alertStr = "Asset successfully enabled";
			    activeMsgNode.innerHTML = alertStr;
			    activeMsgNode.style.display = "block";
			    // reset message node
			    activeMsgNode = null;
			}
		}
	} 
}
	
// function to process duplicate object request
function processDisableRequest () {
    if (thisEnabledRequest.readyState == 4) {
		if (thisEnabledRequest.status == 200) {
		    if (thisEnabledRequest.responseText != 0 ) {
			    activeMsgNode.style.fontWeight = "bold";
			    activeMsgNode.style.color = "Green";
			    var alertStr = "";
			    if (activeMsgNode.id.match('Package')) alertStr = "Package successfully disabled";
                else if (activeMsgNode.id.match('Event')) alertStr = "Event successfully disabled";
                else if (activeMsgNode.id.match('Combo')) alertStr = "Combo successfully disabled";
                else if (activeMsgNode.id.match('Asset')) alertStr = "Asset successfully disabled";
			    activeMsgNode.innerHTML = alertStr;
			    activeMsgNode.style.display = "block";
			    // reset message node
			    activeMsgNode = null;
			}
		}
	} 
}

// function to cover the page to prevent changes while alert is showing
function coverPageForAlert(alert) {
    $('pageCover').style.height = window.innerHeight + "px";
    $('pageCover').style.width = window.innerWidth + "px";
    $('pageCover').style.zIndex = alert.parentNode.style.zIndex - 1;
    $('pageCover').style.display = "block";
}

// function to uncover page
function uncoverPageForAlert() {
    $('pageCover').style.display = "none";
}

// function to check custom color fields on textbox change
function customColorCheck(e) {
    // first check RGB or CMYK
    var colorType = "";
    var letter = e.id[e.id.length - 1];
    colorType = (letter.match(/R|G|B/)) ? "RGB" : "CMYK";
    // based on color type check fields and enable or disable as needed
    if (colorType == "RGB") {
        // check to see if all RGB fields are blank
        var blankRGB = false;
        blankRGB = ($('txtCustomColor_R').value == "" && $('txtCustomColor_G').value == ""
                    && $('txtCustomColor_B').value == "") ? true : false;
        
        // enable all CMYK fields if all RGB is blank
        if (blankRGB) {
            $('txtCustomColor_C').removeAttribute('disabled');
            $('txtCustomColor_M').removeAttribute('disabled');
            $('txtCustomColor_Y').removeAttribute('disabled');
            $('txtCustomColor_K').removeAttribute('disabled');
            // also remove any alerts and clear hex
            $('customColorAlert').style.display = "none";
            $('customColorHexAlert').style.display = "none";
            $('txtCustomColor_Hex').value = "";
            $('customColorExample').style.borderColor = "#BEBEBE";
            $('customColorExample').style.backgroundColor = "#FFFFFF";
        } else { // handle input of RGB value
            // blank out and disable all CMYK
            $('txtCustomColor_C').value = "";
            $('txtCustomColor_M').value = "";
            $('txtCustomColor_Y').value = "";
            $('txtCustomColor_K').value = "";
            $('txtCustomColor_C').setAttribute('disabled', 'disabled');
            $('txtCustomColor_M').setAttribute('disabled', 'disabled');
            $('txtCustomColor_Y').setAttribute('disabled', 'disabled');
            $('txtCustomColor_K').setAttribute('disabled', 'disabled');
            
            // check validity of all non-blank values
            var valueR = $('txtCustomColor_R').value.trim();
            var valueG = $('txtCustomColor_G').value.trim();
            var valueB = $('txtCustomColor_B').value.trim();
            var validR = (valueR != "") ? ((isNaN(valueR) || valueR < 0 || valueR > 255) ? false : true) : true;
            var validG = (valueG != "") ? ((isNaN(valueG) || valueG < 0 || valueG > 255) ? false : true) : true;
            var validB = (valueB != "") ? ((isNaN(valueB) || valueB < 0 || valueB > 255) ? false : true) : true;
            
            // check if RGB values are valid
            if (!(validR && validG && validB)) { // not valid
                // if not valid, remove hex value and alert
                $('txtCustomColor_Hex').value = "";
                $('customColorExample').style.borderColor = "#BEBEBE";
                $('customColorExample').style.backgroundColor = "#FFFFFF";
                $('customColorHexAlert').style.display = "none";
                $('customColorAlert').innerHTML = "RGB values must be numbers in the range 0-255";
                $('customColorAlert').style.display = "block";
            } else {  // valid
                // clear any alerts
                $('customColorAlert').style.display = "none";
                $('customColorHexAlert').style.display = "none";
                // update hex value when all RGB values are complete and valid
                var completeRGB = false;
                completeRGB = (valueR != "" && valueG != ""
                    && valueB != "") ? true : false;                
                if (completeRGB) {
                    var hexValue = rgb2hex(valueR, valueG, valueB);
                    $('txtCustomColor_Hex').value = hexValue;
                    $('customColorExample').style.borderColor = "#" + hexValue;
                    $('customColorExample').style.backgroundColor = "#" + hexValue;
                } else {
                    $('txtCustomColor_Hex').value = "";
                    $('customColorHexAlert').style.display = "none";
                    $('customColorExample').style.borderColor = "#BEBEBE";
                    $('customColorExample').style.backgroundColor = "#FFFFFF";
                }
            }            
        }
    } else { 
        // check to see if all CMYK fields are blank
        var blankCMYK = false;
        blankCMYK = ($('txtCustomColor_C').value == "" && $('txtCustomColor_M').value == ""
                    && $('txtCustomColor_Y').value == "" && $('txtCustomColor_K').value == "") ? true : false;
        
        // enable all RGB fields if all CMYK is blank
        if (blankCMYK) {
            $('txtCustomColor_R').removeAttribute('disabled');
            $('txtCustomColor_G').removeAttribute('disabled');
            $('txtCustomColor_B').removeAttribute('disabled');
            // also remove any alerts and clear hex
            $('customColorAlert').style.display = "none";
            $('customColorHexAlert').style.display = "none";
            $('txtCustomColor_Hex').value = "";
            $('customColorExample').style.borderColor = "#BEBEBE";
            $('customColorExample').style.backgroundColor = "#FFFFFF";
        } else {
            // blank out and disable all RGB
            $('txtCustomColor_R').value = "";
            $('txtCustomColor_G').value = "";
            $('txtCustomColor_B').value = "";
            $('txtCustomColor_R').setAttribute('disabled', 'disabled');
            $('txtCustomColor_G').setAttribute('disabled', 'disabled');
            $('txtCustomColor_B').setAttribute('disabled', 'disabled');
            
            // check validity of all non-blank values
            var valueC = $('txtCustomColor_C').value.trim();
            var valueM = $('txtCustomColor_M').value.trim();
            var valueY = $('txtCustomColor_Y').value.trim();
            var valueK = $('txtCustomColor_K').value.trim();
            var validC = (valueC != "") ? ((isNaN(valueC) || valueC < 0 || valueC > 100) ? false : true) : true;
            var validM = (valueM != "") ? ((isNaN(valueM) || valueM < 0 || valueM > 100) ? false : true) : true;
            var validY = (valueY != "") ? ((isNaN(valueY) || valueY < 0 || valueY > 100) ? false : true) : true;   
            var validK = (valueK != "") ? ((isNaN(valueK) || valueK < 0 || valueK > 100) ? false : true) : true;         
            
            // check if CMYK values are valid
            if (!(validC && validM && validY && validK)) { // not valid
                // if not valid, remove hex value and alert
                $('txtCustomColor_Hex').value = "";
                $('customColorExample').style.borderColor = "#BEBEBE";
                $('customColorExample').style.backgroundColor = "#FFFFFF";
                $('customColorHexAlert').style.display = "none";
                $('customColorAlert').innerHTML = "CMYK values must be numbers in the range 0-100";
                $('customColorAlert').style.display = "block";
            } else { // valid
                // clear any alerts
                $('customColorAlert').style.display = "none";
                $('customColorHexAlert').style.display = "none";
                // update hex value when all CMYK values are complete
                var completeCMYK = false;
                completeCMYK = ($('txtCustomColor_C').value != "" && $('txtCustomColor_M').value != ""
                    && $('txtCustomColor_Y').value != "" && $('txtCustomColor_K').value != "") ? true : false;                
                if (completeCMYK) {
                    var hexValue = cmyk2hex(valueC, valueM, valueY, valueK);
                    $('txtCustomColor_Hex').value = hexValue;
                    $('customColorExample').style.borderColor = "#" + hexValue;
                    $('customColorExample').style.backgroundColor = "#" + hexValue;
                 } else {
                    $('txtCustomColor_Hex').value = "";
                    $('customColorHexAlert').style.display = "none";
                    $('customColorExample').style.borderColor = "#BEBEBE";
                    $('customColorExample').style.backgroundColor = "#FFFFFF";
                }
            }            
        }
    }    
}

// function to hide custom font color tag popup
function hideCustomFontColorTag() {
    // reset all custom color values
    activeTickerEditor = null;
    $('customColorAlert').innerHTML = "";
    $('customColorAlert').style.display = "none";
    $('customColorHexAlert').style.display = "none";
    $('txtCustomColor_R').value = "";
    $('txtCustomColor_G').value = "";
    $('txtCustomColor_B').value = "";
    $('txtCustomColor_C').value = "";
    $('txtCustomColor_M').value = "";
    $('txtCustomColor_Y').value = "";
    $('txtCustomColor_K').value = "";
    $('txtCustomColor_Hex').value = "";
    $('customColorExample').style.borderColor = "#BEBEBE";
    $('customColorExample').style.backgroundColor = "#FFFFFF";
    $('txtCustomColor_R').removeAttribute('disabled');
    $('txtCustomColor_G').removeAttribute('disabled');
    $('txtCustomColor_B').removeAttribute('disabled');
    $('txtCustomColor_C').removeAttribute('disabled');
    $('txtCustomColor_M').removeAttribute('disabled');
    $('txtCustomColor_Y').removeAttribute('disabled');
    $('txtCustomColor_K').removeAttribute('disabled');
    $('customFontColorPopup').style.display = "none";
}

// function to update the color div while user is editing the hex field
function hexKeyUpEvent() {

    // check validity of hex
    var valueHex = $('txtCustomColor_Hex').value.trim();
    if (valueHex != "" && !(valueHex.match(/^([0-9]|[A-F]|[a-f]){6}$/))) { // not valid hex
        $('customColorExample').style.borderColor = "#BEBEBE";
        $('customColorExample').style.backgroundColor = "#FFFFFF";
    } else {  // valid and show color
        $('customColorExample').style.borderColor = "#" + valueHex;
        $('customColorExample').style.backgroundColor = "#" + valueHex;
	}
}

// function to check hex field on textbox change
function customColorCheckHex() {
    // check validity of hex value
    var valueHex = $('txtCustomColor_Hex').value.trim();
    if (valueHex != "" && !(valueHex.match(/^([0-9]|[A-F]|[a-f]){6}$/))) { // not valid hex
        $('customColorHexAlert').style.display = "block";
        $('customColorHexAlert').focus();
    } else {
        $('customColorHexAlert').style.display = "none";
	}
}

// function to check hex field on textbox change
function selectedColorCheckHexMD() {
    // check validity of hex value
    var valueHex = $('selectedColorHexMD').value.trim();
    if (valueHex != "" && !(valueHex.match(/^([0-9]|[A-F]|[a-f]){6}$/))) { // not valid hex
        $('colorSelectHexAlertMD').style.display = "block";
        $('colorSelectHexAlertMD').focus();
        return false;
    } else {
        $('colorSelectHexAlertMD').style.display = "none";
        return true;
	}
}

// function to insert a custom font color tag
function insertCustomFontColorTag() {
    // check validity of hex value
    var valueHex = $('txtCustomColor_Hex').value.trim();
    if (valueHex != "") {
        if (!(valueHex.match(/^([0-9]|[A-F]|[a-f]){6}$/))) { // not valid hex
            $('customColorHexAlert').style.display = "block";
            $('customColorHexAlert').focus();
        } else {
            // create font color tag string and insert
	        var tagStr = "[Color Val=\"#" + $('txtCustomColor_Hex').value + "\"]";
	        activeTickerEditor.insertAtCursor(tagStr);
	        hideCustomFontColorTag();
	    }
	} else {  // alert if blank
        $('customColorHexAlert').style.display = "block";
        $('customColorHexAlert').focus();	
	}
}